package com.hthl.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hthl.config.ApplicationContextProvider;
import com.hthl.entity.CollectData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class PollThread implements Runnable {

    private String message;

    public PollThread(String message) {
        this.message = message;
    }


    @Override
    public void run() {
        log.info("消息被消费，消息为：{}", message);
        try {
            sendMessage(message);
        } catch (Exception e) {
            log.error("推送socket 消息异常", e);
        }
    }

    private void replace$numberDecimal(String messsage){

    }

    /**
     * 主动发送消息给页面
     *
     * @param message
     */
    public void sendMessage(String message) {
        ConcurrentHashMap<Session, Integer> cachedSessions = SessionHolder.getCachedSessions();
        Map map = JSON.parseObject(message, Map.class);
        Integer messageEnterpriseId = (Integer) map.get("enterpriseId");
        if (messageEnterpriseId == null) {
            log.warn("推送的异常数据，无 enterpriseId 已丢弃。消息：{}", message);
            return;
        }

        log.info("开始推送websocket msg......");
        for (Map.Entry<Session, Integer> entry : cachedSessions.entrySet()) {
            Session session = entry.getKey();
            Integer enterpriseId = entry.getValue();
            if (matchConditionPushMsg(enterpriseId, map)) {
                try {
                    CollectData collectData = JSONObject.parseObject(message,CollectData.class);
                    if(isAlarm(collectData)){
                        collectData.setType(CollectData.Type.ALARM.ordinal());
                    }
                    session.getBasicRemote().sendText(JSON.toJSONString(collectData));
                    log.info("成功推送企业：{}", enterpriseId);
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
        }
    }

    /**
     * $isAlarm 判断是否报警
     *
     * @param collectData 采集的数据集合
     * @return true 含有报警信息  false 不含有报警信息
     */
    private boolean isAlarm(CollectData collectData) {
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(collectData.getDataDetailVos())) {
            return false;
        }
        for (CollectData.ParamDetail paramDetail : collectData.getDataDetailVos()) {
            if (paramDetail.getAlarmType() != null) {
                return true;
            }
        }
        return false;
    }

    private boolean matchConditionPushMsg(Integer enterpriseId, Map map) {
        Integer mEnterpriseId = (Integer) map.get("enterpriseId");
        if (mEnterpriseId != null && mEnterpriseId.equals(enterpriseId)) {
            log.info("匹配是供方企业id");
            return true;
        }
        Integer useEnterpriseId = (Integer) map.get("useEnterpriseId");
        if (useEnterpriseId != null && useEnterpriseId.equals(enterpriseId)) {
            log.info("匹配是用方企业id");
            return true;
        }
        Set<Integer> partnerId = (Set<Integer>) map.get("partnerId");
        if (!CollectionUtils.isEmpty(partnerId) && partnerId.contains(enterpriseId)) {
            log.info("匹配是合作方企业id");
            return true;
        }
        return false;
    }
}
